<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SessionBox 调试页面</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .debug-section {
            background: white;
            margin: 20px 0;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .debug-button {
            background: #4285f4;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 4px;
            cursor: pointer;
            margin: 8px;
            font-size: 14px;
        }
        .debug-button:hover {
            background: #3367d6;
        }
        .debug-button.danger {
            background: #ea4335;
        }
        .debug-button.danger:hover {
            background: #d93025;
        }
        .result {
            margin-top: 15px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 4px;
            border-left: 4px solid #4285f4;
            white-space: pre-wrap;
            font-family: monospace;
            font-size: 12px;
            max-height: 300px;
            overflow-y: auto;
        }
        .result.success {
            border-left-color: #34a853;
            background: #e8f5e8;
        }
        .result.error {
            border-left-color: #ea4335;
            background: #fce8e6;
        }
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }
        .status-indicator.online {
            background: #34a853;
        }
        .status-indicator.offline {
            background: #ea4335;
        }
        h1 {
            color: #1a73e8;
            text-align: center;
        }
        h2 {
            color: #333;
            border-bottom: 2px solid #e8eaed;
            padding-bottom: 8px;
        }
    </style>
</head>
<body>
    <h1>🔧 SessionBox 扩展调试工具</h1>
    
    <div class="debug-section">
        <h2><span id="statusIndicator" class="status-indicator offline"></span>扩展状态检测</h2>
        <button class="debug-button" onclick="checkExtensionStatus()">检测扩展状态</button>
        <button class="debug-button" onclick="checkBackgroundService()">检查后台服务</button>
        <div id="statusResult" class="result">点击按钮开始检测...</div>
    </div>
    
    <div class="debug-section">
        <h2>📨 消息通信测试</h2>
        <button class="debug-button" onclick="testGetSessions()">获取会话列表</button>
        <button class="debug-button" onclick="testCreateSession()">创建测试会话</button>
        <button class="debug-button" onclick="testCurrentSession()">获取当前会话</button>
        <div id="messageResult" class="result">等待测试...</div>
    </div>
    
    <div class="debug-section">
        <h2>💾 存储系统测试</h2>
        <button class="debug-button" onclick="testStorage()">测试存储读写</button>
        <button class="debug-button" onclick="viewStorageData()">查看存储数据</button>
        <button class="debug-button danger" onclick="clearStorageData()">清空存储数据</button>
        <div id="storageResult" class="result">等待测试...</div>
    </div>
    
    <div class="debug-section">
        <h2>🔧 故障排除工具</h2>
        <button class="debug-button" onclick="reloadExtension()">重新加载扩展</button>
        <button class="debug-button" onclick="resetExtensionState()">重置扩展状态</button>
        <button class="debug-button" onclick="exportDebugInfo()">导出调试信息</button>
        <div id="troubleshootResult" class="result">选择操作...</div>
    </div>

    <script>
        let debugLog = [];
        
        function log(message, type = 'info') {
            const timestamp = new Date().toLocaleTimeString();
            debugLog.push({ timestamp, message, type });
            console.log(`[${timestamp}] ${message}`);
        }
        
        function updateResult(elementId, message, isSuccess = null) {
            const element = document.getElementById(elementId);
            element.textContent = message;
            
            if (isSuccess === true) {
                element.className = 'result success';
            } else if (isSuccess === false) {
                element.className = 'result error';
            } else {
                element.className = 'result';
            }
        }
        
        function updateStatus(isOnline) {
            const indicator = document.getElementById('statusIndicator');
            indicator.className = `status-indicator ${isOnline ? 'online' : 'offline'}`;
        }

        async function checkExtensionStatus() {
            log('开始检测扩展状态', 'info');
            
            try {
                if (typeof chrome === 'undefined') {
                    throw new Error('Chrome API 不可用');
                }
                
                if (!chrome.runtime) {
                    throw new Error('chrome.runtime 不可用');
                }
                
                if (!chrome.runtime.sendMessage) {
                    throw new Error('chrome.runtime.sendMessage 不可用');
                }
                
                // 尝试发送一个简单的消息
                const response = await new Promise((resolve, reject) => {
                    const timeout = setTimeout(() => {
                        reject(new Error('消息发送超时'));
                    }, 3000);
                    
                    chrome.runtime.sendMessage({ action: 'ping' }, (response) => {
                        clearTimeout(timeout);
                        if (chrome.runtime.lastError) {
                            reject(new Error(chrome.runtime.lastError.message));
                        } else {
                            resolve(response);
                        }
                    });
                });
                
                updateStatus(true);
                updateResult('statusResult', '✅ 扩展状态正常\n' + 
                    '- Chrome API 可用\n' + 
                    '- 消息通信正常\n' + 
                    '- 后台服务响应', true);
                log('扩展状态检测完成：正常', 'success');
                
            } catch (error) {
                updateStatus(false);
                updateResult('statusResult', `❌ 扩展状态异常\n错误信息：${error.message}`, false);
                log(`扩展状态检测失败：${error.message}`, 'error');
            }
        }

        async function checkBackgroundService() {
            try {
                const response = await sendMessageSafely({ action: 'getSessions' });
                
                if (response && response.success) {
                    updateResult('statusResult', `✅ 后台服务正常\n会话数量：${response.sessions.length}`, true);
                } else {
                    updateResult('statusResult', `⚠️ 后台服务异常\n响应：${JSON.stringify(response)}`, false);
                }
            } catch (error) {
                updateResult('statusResult', `❌ 后台服务不可用\n错误：${error.message}`, false);
            }
        }

        async function testGetSessions() {
            try {
                log('测试获取会话列表', 'info');
                const response = await sendMessageSafely({ action: 'getSessions' });
                
                updateResult('messageResult', 
                    `✅ 获取会话成功\n` +
                    `响应：${JSON.stringify(response, null, 2)}`, true);
                log('获取会话列表成功', 'success');
                
            } catch (error) {
                updateResult('messageResult', `❌ 获取会话失败\n错误：${error.message}`, false);
                log(`获取会话列表失败：${error.message}`, 'error');
            }
        }

        async function testCreateSession() {
            try {
                log('测试创建会话', 'info');
                const config = {
                    name: `调试会话 ${Date.now()}`,
                    color: '#4285f4',
                    fingerprintProtection: false
                };
                
                const response = await sendMessageSafely({
                    action: 'createSession',
                    config: config
                });
                
                updateResult('messageResult', 
                    `✅ 创建会话成功\n` +
                    `配置：${JSON.stringify(config, null, 2)}\n` +
                    `响应：${JSON.stringify(response, null, 2)}`, true);
                log('创建会话成功', 'success');
                
            } catch (error) {
                updateResult('messageResult', `❌ 创建会话失败\n错误：${error.message}`, false);
                log(`创建会话失败：${error.message}`, 'error');
            }
        }

        async function testCurrentSession() {
            try {
                log('测试获取当前会话', 'info');
                const response = await sendMessageSafely({ action: 'getCurrentSession' });
                
                updateResult('messageResult', 
                    `✅ 获取当前会话成功\n` +
                    `响应：${JSON.stringify(response, null, 2)}`, true);
                log('获取当前会话成功', 'success');
                
            } catch (error) {
                updateResult('messageResult', `❌ 获取当前会话失败\n错误：${error.message}`, false);
                log(`获取当前会话失败：${error.message}`, 'error');
            }
        }

        async function testStorage() {
            try {
                log('测试存储功能', 'info');
                
                // 测试写入
                const testData = { test_key: `test_value_${Date.now()}` };
                await chrome.storage.local.set(testData);
                
                // 测试读取
                const result = await chrome.storage.local.get('test_key');
                
                if (result.test_key === testData.test_key) {
                    updateResult('storageResult', '✅ 存储功能正常\n写入和读取测试通过', true);
                    log('存储功能测试通过', 'success');
                } else {
                    throw new Error('读取的数据与写入的数据不匹配');
                }
                
                // 清理测试数据
                await chrome.storage.local.remove('test_key');
                
            } catch (error) {
                updateResult('storageResult', `❌ 存储功能异常\n错误：${error.message}`, false);
                log(`存储功能测试失败：${error.message}`, 'error');
            }
        }

        async function viewStorageData() {
            try {
                const data = await chrome.storage.local.get(null);
                updateResult('storageResult', 
                    `📋 当前存储数据：\n${JSON.stringify(data, null, 2)}`);
                log('查看存储数据完成', 'info');
            } catch (error) {
                updateResult('storageResult', `❌ 无法读取存储数据\n错误：${error.message}`, false);
            }
        }

        async function clearStorageData() {
            if (!confirm('确定要清空所有存储数据吗？这将删除所有会话！')) {
                return;
            }
            
            try {
                await chrome.storage.local.clear();
                updateResult('storageResult', '✅ 存储数据已清空', true);
                log('存储数据已清空', 'info');
            } catch (error) {
                updateResult('storageResult', `❌ 清空存储数据失败\n错误：${error.message}`, false);
            }
        }

        function reloadExtension() {
            updateResult('troubleshootResult', 
                '🔄 请手动重新加载扩展：\n' +
                '1. 打开 chrome://extensions/\n' +
                '2. 找到 SessionBox 扩展\n' +
                '3. 点击"重新加载"按钮');
            log('提示用户重新加载扩展', 'info');
        }

        async function resetExtensionState() {
            try {
                await clearStorageData();
                updateResult('troubleshootResult', 
                    '✅ 扩展状态已重置\n' +
                    '- 存储数据已清空\n' +
                    '- 请重新加载扩展以完成重置', true);
                log('扩展状态重置完成', 'info');
            } catch (error) {
                updateResult('troubleshootResult', `❌ 重置失败\n错误：${error.message}`, false);
            }
        }

        function exportDebugInfo() {
            const debugInfo = {
                timestamp: new Date().toISOString(),
                userAgent: navigator.userAgent,
                url: location.href,
                logs: debugLog,
                chromeVersion: navigator.userAgent.match(/Chrome\/([0-9.]+)/)?.[1] || 'Unknown'
            };
            
            const blob = new Blob([JSON.stringify(debugInfo, null, 2)], {
                type: 'application/json'
            });
            
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `sessionbox-debug-${new Date().toISOString().split('T')[0]}.json`;
            a.click();
            
            URL.revokeObjectURL(url);
            
            updateResult('troubleshootResult', '✅ 调试信息已导出');
            log('调试信息导出完成', 'info');
        }

        // 安全的消息发送函数
        function sendMessageSafely(message, timeout = 5000) {
            return new Promise((resolve, reject) => {
                const timer = setTimeout(() => {
                    reject(new Error('消息发送超时'));
                }, timeout);

                try {
                    chrome.runtime.sendMessage(message, (response) => {
                        clearTimeout(timer);
                        
                        if (chrome.runtime.lastError) {
                            reject(new Error(chrome.runtime.lastError.message));
                        } else {
                            resolve(response);
                        }
                    });
                } catch (error) {
                    clearTimeout(timer);
                    reject(error);
                }
            });
        }

        // 页面加载时自动检测
        window.addEventListener('load', () => {
            log('调试页面加载完成', 'info');
            checkExtensionStatus();
        });
    </script>
</body>
</html> 